var express = require('express');
var router = express.Router();
var log4js = require('log4js');
var moment = require('moment');
var fs = require('fs');
var co = require('co');
var readline = require('readline');

var application = require('../app/Application');

var logManager = application.getManager('log');

var common = function (req) {
  var arg = {};
  var body = req.body;
  ['appversion',
    'stbid',
    'stbmodule',
    'platform',
    'biz',
    'sdkversion',
    'actioncode',
    'actionname',
    'package',
    'userid',
    'flavor']
    .forEach(function(item) {
      if (body[item]) {
        arg[item] = body[item];
      }
  });
  return arg;
};

var _notifyLogging = function () {
  logManager.onLogging();
};

var _logWithArguments = function (req, res, arguments, logType) {
  try {
    var arg = common(req);
    var body = req.body;
    arguments.forEach(function(item) {
        arg[item] = body[item];
      });
    var log = log4js.getLogger(logType);
    log.trace(JSON.stringify(arg));
    _notifyLogging();
    res.send('ok');
  } catch (err) {
    res.send('err', err);
  }
};

// 处理跨域请求
router.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With');
  res.setHeader('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
  next();
});

router.post('/app', function(req, res) {
  _logWithArguments(req, res,
    [
      'app'
    ], 'app');

});

router.post('/page', function(req, res) {
  _logWithArguments(req, res,
    [
      'pagecode',
      'pagename'
    ], 'page');
});

router.post('/content', function(req, res) {
  _logWithArguments(req, res,
    [
      'categorycode',
      'categoryname',
      'contentcode',
      'contentname',
      'duration'
    ], 'content');
});

router.post('/event', function(req, res) {
  _logWithArguments(req, res,
    [
      'eventcode',
      'eventname',
      'eventdata'
    ], 'event');
});

router.post('/order', function(req, res) {
  _logWithArguments(req, res,
    [
      'ordercode',
      'subjectcode',
      'subjectname',
      'subjecttype',
      'subjectprice'
    ], 'order');
});

router.post('/recycle', function (req, res) {
  _notifyLogging();
  // 加载从指定日期起的log文件,然后根据时间,加载日志内容
  var body = req.body;
  var timestamps = {};
  ['app', 'page', 'content', 'event', 'order']
    .forEach(function (item) {
      if (body[item] !== undefined) {
        timestamps[item] = parseInt(body[item]);
      }
  });
  var logFiles = logManager.logFilesFrom(timestamps);
  var logs = {};

  var readLines = function (filePath, options) {
    return new Promise(function (resolve) {
      var res = [];
      var rl = readline.createInterface({
        input: fs.createReadStream(filePath)
      });
      rl.on('line', function (line) {
        var logContent = logManager.getLog(line, options);
        if (logContent) {
          res.push(logContent);
        }
      });
      rl.on('close', function () {
        resolve(res);
      })
    });
  };

  co(function * () {
    for (var key in logFiles) {
      var files = logFiles[key];
      if (!logs[key]) {
        logs[key] = {
          lastTimestamp: 0,
          logs: []
        };
      }
      if (!files) {
        continue;
      }
      var len = files.length;
      // for (var i = 0; i < len; i++) {
      //   var reads = yield readLines(files[i], { timestamp: timestamps[key] });
      //   if (reads) {
      //     reads.forEach(function (item) {
      //       logs[key].lastTimestamp = Math.max(logs[key].lastTimestamp, item.timestamp);
      //       logs[key].logs.push(item);
      //     });
      //   }
      // }
      if (len > 0) {
        var reads = yield readLines(files[0], { timestamp: timestamps[key] });
        if (reads) {
          reads.forEach(function (item) {
            logs[key].lastTimestamp = Math.max(logs[key].lastTimestamp, item.timestamp);
            logs[key].logs.push(item);
          });
        }
        logManager.removeLogFilesFrom(key, moment(timestamps[key], 'X').format(), 3 * 24 * 3600);
      }

    }

    // logManager.clearExpiredLogs();
    res.json(logs);
  })

});

module.exports = router;
